<?php

namespace Framework\Foundation\Database;

use Framework\Foundation\Config;

/**
 * @method static \Envms\FluentPDO\Queries\Select from(?string $table = null, ?int $primaryKey = null)
 * @method static \Envms\FluentPDO\Queries\Insert insertInto(?string $table = null, array $values = [])
 * @method static \Envms\FluentPDO\Queries\Update update(?string $table = null, $set = [], ?int $primaryKey = null)
 * @method static \Envms\FluentPDO\Queries\Delete delete(?string $table = null, ?int $primaryKey = null)
 * @method static \Envms\FluentPDO\Queries\Delete deleteFrom(?string $table = null, ?int $primaryKey = null)
 * @method static \PDO getPdo()
 * @method static \Envms\FluentPDO\Structure getStructure()
 * @method static void close()
 * @method static \Envms\FluentPDO\Query setTableName(?string $table = '', string $prefix = '', string $separator = '')
 * @method static string getFullTableName()
 * @method static string getPrefix()
 * @method static string getSeparator()
 * @method static string getTable()
 * @method static void throwExceptionOnError(bool $flag)
 * @method static void convertTypes(bool $read, bool $write)
 * @method static void convertReadTypes(bool $flag)
 * @method static void convertWriteTypes(bool $flag)
 *
 * @see \Envms\FluentPDO\Query
 */
class FDB
{
    protected static $connections;

    public static function connection($name, array $conf = [])
    {
        if (isset(self::$connections[$name])) {
            return self::$connections[$name];
        }

        return self::newConnect($name, $conf);
    }

    public static function newConnect($name, array $conf = [], $debug = false)
    {
        if (empty($conf)) {
            $conf = self::getConfig($name);
        }
        if (empty($conf)) {
            return null;
        }

        $pdo = new \PDO($conf['dsn'], $conf['username'], $conf['password']);
        $fluent = new \Envms\FluentPDO\Query($pdo);
        if (false != $debug) {
            $fluent->debug = $debug;
        }
        return $fluent;
    }

    public static function getConfig($name)
    {
        return Config::instance()->get('database.mysql.' . $name);
    }

    public static function __callStatic($name, $arguments)
    {
        if (!isset(self::$connections['default'])) {
            self::$connections['default'] = self::newConnect('default');
        }

        return call_user_func_array([self::$connections['default'], $name], $arguments);
    }

    public static function connectionWithDebug($debug, $name = 'default', array $conf = [])
    {
        return self::newConnect($name, $conf, $debug);
    }

    public function selectRaw($sql, $params)
    {
    }

    public function execRaw($sql, $params)
    {
    }
}
